package com.tianji.promotion.strategy.discount;

import com.tianji.promotion.anoontation.DiscountTypeFlag;
import com.tianji.promotion.enums.DiscountType;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;
@Component
public class DiscountStrategy implements ApplicationContextAware {

    private static EnumMap<DiscountType, Discount> strategies;

    //    static {
//        strategies = new EnumMap<>(DiscountType.class);
//        strategies.put(DiscountType.NO_THRESHOLD, new NoThresholdDiscount());
//        strategies.put(DiscountType.PER_PRICE_DISCOUNT, new PerPriceDiscount());
//        strategies.put(DiscountType.RATE_DISCOUNT, new RateDiscount());
//        strategies.put(DiscountType.PRICE_DISCOUNT, new PriceDiscount());
//    }
//
    public static Discount getDiscount(DiscountType type) {
        return strategies.get(type);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        strategies = new EnumMap<>(DiscountType.class);
        Map<String, Discount> beans = applicationContext.getBeansOfType(Discount.class);
        beans.values().stream().forEach(bean -> {
            DiscountType key = bean.getClass().getAnnotation(DiscountTypeFlag.class).value();
            strategies.put(key, bean);
        });
    }
}
